# open函数打开一个文件，没有文件会新建，但是路径不对会报错
# 指定文件名，方法（读，写，追加），编码格式


# 保存到文件
output = open("output.md", "w", encoding="utf-8")
content = """
# 编码
>>> '训练营'.encode("utf-8")
b'\xe8\xae\xad\xe7\xbb\x83\xe8\x90\xa5'


# 解码
>>> a = '训练营'.encode("utf-8")
>>> a
b'\xe8\xae\xad\xe7\xbb\x83\xe8\x90\xa5'
>>> a.decode("utf")
'训练营'


# Create(创建)
>>> a = 'a'
>>> a += 'b'
>>> a
'ab'


# Retrieve(检索)
# 根据索引获取字符
>>> a = 'hello, python'
>>> a[0]
'h'


# find和index
>>> a = 'hello, python'
>>> a.find("p")
7
>>> a.find("@")
-1
>>> a.index("h")
0
>>> a.index("@")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: substring not found


# startswith和endswith
>>> a = "2020-12-25.python.py"
>>> a
'2020-12-25.python.py'
>>> a.startwith("2020")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'str' object has no attribute 'startwith'
>>> a.startswith("2020")
True
>>> a.endswith("py")
True


# Update(更新）
# replace(替换)
>>> a = "hello, python"
>>> a.replace("on", "off")
'hello, pythoff'
>>> a
'hello, python'
>>> b = a.replace("on","off")
>>> b
'hello, pythoff'


# split(分割)
>>> a = "<<python>>, <<go>>, <<c>>, <<java>>"
>>> a.split(",")
['<<python>>', ' <<go>>', ' <<c>>', ' <<java>>']
>>>


# join(拼接)
>>> b = a.split(",")
>>> b
['<<python>>', ' <<go>>', ' <<c>>', ' <<java>>']
>>> b.join(",")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'list' object has no attribute 'join'
>>> ",".join(b)
'<<python>>, <<go>>, <<c>>, <<java>>'


# Delete(删除)
# strip, lstrip, rstrip
>>> a = "       hello, python           "
>>> a.lstrip()
'hello, python\t\t'
>>> a.rstrip()
'\thello, python'
>>> a = "      hello, python      "
>>> a.strip()
'hello, python'
>>> a.lstrip()
'hello, python      '


# format
# 按传入参数默认顺序
>>> a = "ping"
>>> b = "pong"
>>> "play pingpong: {}, {}".format(a, b)
'play pingpong: ping, pong'


# 按指定参数索引
>>> "play pingpong: {0}, {1}, {0}, {1}".format(b, a)
'play pingpong: pong, ping, pong, ping'


# 按关键词参数
>>> "play pingpong: {a}, {b}, {a}, {b}".format(a = a, b = b)
'play pingpong: ping, pong, ping, pong'


# 按变量（推荐，但是只有3.6以上版本才可以使用）
>>> f"playing pingpong: {a}, {b}"
'playing pingpong: ping, pong'


# 小数的表示
>>> "{:.2f}".format(3.1415926)
'3.14'


# %的用法
>>> "playing %s %s" % ("ping","pong")
'playing ping pong'
"""
# 正式写入文件
output.write(content)
# 关闭文件句柄
output.close()


# 读取文件
input = open("output.txt", "r", encoding="utf-8")
# 获取文件中的内容
content = input.read()
print(content)
# 暂时理解为只能读取一遍
content_2 = input.read()
print(content_2)


# 追加文件
output = open("output.txt", "a", encoding="utf-8")
content_a = "\nhello, python"
# 正式写入文件
output.write(content_a)
output.close()